import { defineStore } from 'pinia'
import { getCodeApi } from '@/api/login'
import { TypeLogin } from '@/types/typeData'
import { loginApi } from '@/api/login'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { Token, User } from '@/types/data'
export default defineStore('user', {
  state: () => {
    return {
      token: localStorage.getItem('token') || ('' as unknown as Token),
      code: '' as string,
      time: localStorage.getItem('time') || ('' as unknown as string),
      asideItem: null,
      userInfo: JSON.parse(localStorage.getItem('user') as any) || {} as User
    }
  },
  actions: {
    async getCode(): Promise<void> {
      const res = await getCodeApi('E40C3B489D1793C2FC8074751677827045549')
      let url =
        'data:image/png;base64,' +
        btoa(
          new Uint8Array(res.data as any).reduce(
            (data, byte) => data + String.fromCharCode(byte),
            ''
          )
        )
      this.code = url
    },
    // 退出登录
    out() {
      this.time = ''
      this.token = ''
      this.code = ''
      this.userInfo = ''
      localStorage.removeItem('itemNmae')
      localStorage.removeItem('loginTime')
      localStorage.removeItem('token')
      localStorage.removeItem('time')
      localStorage.removeItem('path')
      localStorage.removeItem('user')
      router.push('/login')
    },
    // 登录
    async login(data: TypeLogin): Promise<void> {
      const res = await loginApi(data)
      if (res.data.code !== 200) {
        ElMessage.error(res.data.msg)
        this.getCode()
      } else {
        ElMessage({
          message: '登录成功',
          type: 'success',
        })
        const newTime: number = Date.now()
        this.userInfo = res.data.data.user as User
        localStorage.setItem('user', JSON.stringify(res.data.data.user as any))
        localStorage.setItem('loginTime', newTime as any)
        localStorage.setItem('token', res.data.data.token.token as any)
        localStorage.setItem('time', 2000000000000000000n as any)   // 暂时测试时间
        this.token = res.data.data.token.token
        router.push('/')
      }
    },
  },
})
